// Encapsulated initialization for the bar race chart
function createBarRaceChart(containerId, options = {}) {
  // Parameter validation
  if (!containerId || typeof containerId !== 'string') {
    throw new Error('Invalid containerId: must be a non-empty string');
  }
  
  const dom = document.getElementById(containerId);
  if (!dom) {
    throw new Error(`Container not found: ${containerId}`);
  }

  // 全局状态管理 - 移到函数开头
  let showBlue = true;
  let showGreen = true;
  let showYellow = true;  // 新增黄色控制
  let showRed = true;     // 新增红色控制
  let showCyan = true;    // 新增青色控制
  let showGreen2 = true;  // 新增深绿色控制
  let showOrange = true;  // 新增橙色控制

  const myChart = echarts.init(dom, null, {
    renderer: 'canvas',
    useDirtyRect: false
  });

  // 添加错误处理
  myChart.on('error', (params) => {
    console.error('ECharts error:', params);
  });

  let option;

  // Configuration with defaults
  const config = {
    dataCount: options.dataCount || 35, // 增加到35个
    showGreenBars: options.showGreenBars !== false, // default true
    updateIntervalMs: Math.max(100, options.updateIntervalMs || 3000), // minimum 100ms
    autoStart: options.autoStart !== false, // default true
    maxValue: options.maxValue || 200,
    animationDuration: options.animationDuration || 3000,
    barColors: options.barColors || ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452'] // 7种颜色
  };

  // Initial data generation - 为每个类别创建一个数据点
  const originalData = Array.from({ length: config.dataCount }, () => 
    Math.round(Math.random() * config.maxValue)
  );
  const data = [...originalData]; // 工作数据副本

  // State variables
  let updateIntervalMs = config.updateIntervalMs;
  let autoStart = config.autoStart;

  // Generate category labels dynamically
  const categoryLabels = Array.from({ length: config.dataCount }, (_, i) => 
    String.fromCharCode(65 + i) // A, B, C, ...
  );

  // Chart configuration
  option = {
    xAxis: {
      max: 'dataMax',
      axisLabel: {
        formatter: (value) => value.toLocaleString()
      }
    },
    yAxis: {
      type: 'category',
      data: categoryLabels,
      inverse: true,
      animationDuration: 300,
      animationDurationUpdate: 300
    },
    series: [
      {
        name: 'Dynamic Bars',
        type: 'bar',
        data: data,
        itemStyle: {
          color: (params) => {
            // 根据索引位置决定颜色：每5个一组，共7组颜色
            const colorIndex = Math.floor(params.dataIndex / 5);
            return config.barColors[colorIndex] || config.barColors[0];
          }
        },
        label: {
          show: true,
          position: 'right',
          valueAnimation: true,
          formatter: (params) => params.value.toLocaleString()
        },
        barGap: '30%', // 增加柱状图之间的间隔
        barCategoryGap: '20%' // 增加类别之间的间隔
      }
    ],
    legend: {
      show: false
    },
    animationDuration: 500, // 减少初始动画时间到0.5秒
    animationDurationUpdate: 800, // 减少更新动画时间到0.8秒
    animationEasing: 'cubicOut',
    animationEasingUpdate: 'cubicOut',
    // 全局排序配置
    dataset: {
      source: []
    }
  };

  // Update functions (separated)
  function updateDataValues() {
    const updateChance = 0.3; // 增加到30% chance for large update
    const largeUpdateRange = config.maxValue * 5; // 减少大更新的范围，避免数值过大
    const smallUpdateRange = config.maxValue * 0.5; // 增加小更新的范围，让变化更明显
    
    // Update original data
    for (let j = 0; j < originalData.length; ++j) {
      if (Math.random() > (1 - updateChance)) {
        originalData[j] += Math.round(Math.random() * largeUpdateRange);
      } else {
        originalData[j] += Math.round(Math.random() * smallUpdateRange);
      }
      
      // 确保数据不会变成负数
      if (originalData[j] < 0) {
        originalData[j] = Math.abs(originalData[j]);
      }
    }
    
    // 同步到工作数据
    data.length = 0;
    data.push(...originalData);
    
    // 不要直接更新图表，而是通过updateOnce来更新
    // 这样可以确保排序和过滤逻辑正确执行
    console.log('Data values updated:', data);
  }

  // 自定义排序函数 - 基于当前可见数据排序
  function sortByCurrentVisibleData(legendState = null) {
    // 如果没有传入图例状态，默认显示所有
    if (!legendState) {
      legendState = {
        '蓝色柱状图': true,
        '绿色柱状图': true,
        '黄色柱状图': true,
        '红色柱状图': true,
        '青色柱状图': true,
        '深绿色柱状图': true,
        '橙色柱状图': true
      };
    }
    
    // 不要修改全局状态变量，使用局部变量
    const localShowBlue = legendState['蓝色柱状图'] !== false;
    const localShowGreen = legendState['绿色柱状图'] !== false;
    const localShowYellow = legendState['黄色柱状图'] !== false;
    const localShowRed = legendState['红色柱状图'] !== false;
    const localShowCyan = legendState['青色柱状图'] !== false;
    const localShowGreen2 = legendState['深绿色柱状图'] !== false;
    const localShowOrange = legendState['橙色柱状图'] !== false;
    
    // 创建排序数据，包含索引、值和颜色
    const combinedData = originalData.map((value, index) => {
      // 根据索引位置决定颜色：每5个一组，共7组颜色
      const colorIndex = Math.floor(index / 5);
      const color = config.barColors[colorIndex] || config.barColors[0];
      
      return {
        index,
        value,
        color,
        sortValue: value
      };
    });
    
    // 根据图例状态过滤数据
    const filteredData = combinedData.filter(item => {
      // 根据颜色确定应该显示还是隐藏
      const colorIndex = config.barColors.indexOf(item.color);
      if (colorIndex === 0) return localShowBlue;      // 蓝色组
      if (colorIndex === 1) return localShowGreen;     // 绿色组
      if (colorIndex === 2) return localShowYellow;    // 黄色组
      if (colorIndex === 3) return localShowRed;       // 红色组
      if (colorIndex === 4) return localShowCyan;      // 青色组
      if (colorIndex === 5) return localShowGreen2;    // 深绿色组
      if (colorIndex === 6) return localShowOrange;    // 橙色组
      return true; // 默认显示
    });
    
    // 如果没有数据要显示，显示一个空状态
    if (filteredData.length === 0) {
      console.log('No data to display');
      myChart.setOption({
        yAxis: { data: [] },
        series: [{ data: [] }]
      });
      return;
    }
    
    // 按数值降序排序
    filteredData.sort((a, b) => b.sortValue - a.sortValue);
    
    // 重新排列数据
    const newData = [];
    const newLabels = [];
    
    filteredData.forEach(item => {
      newData.push(item.value);
      newLabels.push(categoryLabels[item.index]);
    });
    
    console.log('Updating chart with filtered data:', newData);
    console.log('Filtered labels:', newLabels);
    
    // 更新Y轴标签和系列数据
    myChart.setOption({
      yAxis: {
        data: newLabels
      },
      series: [
        {
          name: 'Dynamic Bars',
          data: newData,
          itemStyle: {
            color: (params) => {
              // 根据当前显示的数据重新计算颜色
              const originalIndex = filteredData[params.dataIndex].index;
              const colorIndex = Math.floor(originalIndex / 5);
              return config.barColors[colorIndex] || config.barColors[0];
            }
          }
        }
      ]
    });
  }

  // 兼容旧函数名
  function sortByTotalValue() {
    sortByCurrentVisibleData();
  }

  function renderSeries() {
    // 现在通过 sortByCurrentVisibleData 来处理渲染
    sortByCurrentVisibleData();
  }

  function updateOnce() {
    // 先更新数据值
    updateDataValues();
    
    // 然后根据当前状态进行排序显示
    const legendState = {
      '蓝色柱状图': showBlue,
      '绿色柱状图': showGreen,
      '黄色柱状图': showYellow,
      '红色柱状图': showRed,
      '青色柱状图': showCyan,
      '深绿色柱状图': showGreen2,
      '橙色柱状图': showOrange
    };
    
    // 强制重新排序和更新图表
    sortByCurrentVisibleData(legendState);
    
    console.log('Chart updated with new data and sorting');
    console.log('Current visibility state:', { showBlue, showGreen, showYellow, showRed, showCyan, showGreen2, showOrange });
  }

  // Initialize chart
  if (option && typeof option === 'object') {
    console.log('Setting initial chart option:', option);
    myChart.setOption(option);
    
    // 初始化时调用排序函数来设置正确的颜色
    const legendState = {
      '蓝色柱状图': showBlue,
      '绿色柱状图': showGreen,
      '黄色柱状图': showYellow,
      '红色柱状图': showRed,
      '青色柱状图': showCyan,
      '深绿色柱状图': showGreen2,
      '橙色柱状图': showOrange
    };
    console.log('Initial legend state:', legendState);
    sortByCurrentVisibleData(legendState);
    
    // 调试：检查图例是否正确显示
    console.log('Chart initialized with legend:', option.legend);
    console.log('Legend data:', option.legend.data);
    console.log('Initial data:', data);
  }

  // Auto update controls
  let intervalId = null;
  
  function startAutoUpdate() {
    if (intervalId != null) return;
    console.log('Starting auto update with interval:', updateIntervalMs, 'ms');
    intervalId = setInterval(() => {
      console.log('Auto update triggered');
      updateOnce();
    }, updateIntervalMs);
  }

  function stopAutoUpdate() {
    if (intervalId == null) return;
    clearInterval(intervalId);
    intervalId = null;
  }

  if (autoStart) {
    console.log('Auto start enabled, starting update cycle...');
    setTimeout(() => {
      console.log('Initial update triggered');
      updateOnce();
    }, 0);
    startAutoUpdate();
  }

  // 全局状态管理
  // let showBlue = true; // Moved to function scope
  // let showGreen = true; // Moved to function scope
  
  // 暂停状态管理
  let isPaused = false;
  
  // Handle window resize with debouncing
  let resizeTimeout;
  function handleResize() {
    clearTimeout(resizeTimeout);
    resizeTimeout = setTimeout(() => {
      myChart.resize();
    }, 100);
  }
  window.addEventListener('resize', handleResize);
  
  // 创建外部控制按钮
  function createControlButtons() {
    const container = document.getElementById(containerId);
    const buttonContainer = document.createElement('div');
    buttonContainer.className = 'chart-controls';
    buttonContainer.style.cssText = `
      position: absolute;
      top: 20px;
      right: 20px;
      display: flex;
      gap: 10px;
      z-index: 1000;
    `;
    
    const blueButton = document.createElement('button');
    blueButton.textContent = '蓝色柱状图';
    blueButton.className = 'control-btn blue-btn';
    blueButton.style.cssText = `
      padding: 8px 16px;
      border: 2px solid #5470c6;
      background: #5470c6;
      color: white;
      border-radius: 5px;
      cursor: pointer;
      font-size: 14px;
      font-weight: bold;
      transition: all 0.3s ease;
    `;
    
    const greenButton = document.createElement('button');
    greenButton.textContent = '绿色柱状图';
    greenButton.className = 'control-btn green-btn';
    greenButton.style.cssText = `
      padding: 8px 16px;
      border: 2px solid #91cc75;
      background: #91cc75;
      color: white;
      border-radius: 5px;
      cursor: pointer;
      font-size: 14px;
      font-weight: bold;
      transition: all 0.3s ease;
    `;
    
    // 新增黄色按钮
    const yellowButton = document.createElement('button');
    yellowButton.textContent = '黄色柱状图';
    yellowButton.className = 'control-btn yellow-btn';
    yellowButton.style.cssText = `
      padding: 8px 16px;
      border: 2px solid #fac858;
      background: #fac858;
      color: white;
      border-radius: 5px;
      cursor: pointer;
      font-size: 14px;
      font-weight: bold;
      transition: all 0.3s ease;
    `;
    
    // 新增红色按钮
    const redButton = document.createElement('button');
    redButton.textContent = '红色柱状图';
    redButton.className = 'control-btn red-btn';
    redButton.style.cssText = `
      padding: 8px 16px;
      border: 2px solid #ee6666;
      background: #ee6666;
      color: white;
      border-radius: 5px;
      cursor: pointer;
      font-size: 14px;
      font-weight: bold;
      transition: all 0.3s ease;
    `;
    
    // 新增青色按钮
    const cyanButton = document.createElement('button');
    cyanButton.textContent = '青色柱状图';
    cyanButton.className = 'control-btn cyan-btn';
    cyanButton.style.cssText = `
      padding: 8px 16px;
      border: 2px solid #73c0de;
      background: #73c0de;
      color: white;
      border-radius: 5px;
      cursor: pointer;
      font-size: 14px;
      font-weight: bold;
      transition: all 0.3s ease;
    `;
    
    // 新增深绿色按钮
    const green2Button = document.createElement('button');
    green2Button.textContent = '深绿色柱状图';
    green2Button.className = 'control-btn green2-btn';
    green2Button.style.cssText = `
      padding: 8px 16px;
      border: 2px solid #3ba272;
      background: #3ba272;
      color: white;
      border-radius: 5px;
      cursor: pointer;
      font-size: 14px;
      font-weight: bold;
      transition: all 0.3s ease;
    `;
    
    // 新增橙色按钮
    const orangeButton = document.createElement('button');
    orangeButton.textContent = '橙色柱状图';
    orangeButton.className = 'control-btn orange-btn';
    orangeButton.style.cssText = `
      padding: 8px 16px;
      border: 2px solid #fc8452;
      background: #fc8452;
      color: white;
      border-radius: 5px;
      cursor: pointer;
      font-size: 14px;
      font-weight: bold;
      transition: all 0.3s ease;
    `;
    
    // 添加暂停/继续按钮
    const pauseButton = document.createElement('button');
    pauseButton.textContent = '暂停';
    pauseButton.className = 'control-btn pause-btn';
    pauseButton.style.cssText = `
      padding: 8px 16px;
      border: 2px solid #ff6b6b;
      background: #ff6b6b;
      color: white;
      border-radius: 5px;
      cursor: pointer;
      font-size: 14px;
      font-weight: bold;
      transition: all 0.3s ease;
    `;
    
    function updateButtonStates() {
      blueButton.style.opacity = showBlue ? '1' : '0.5';
      greenButton.style.opacity = showGreen ? '1' : '0.5';
      yellowButton.style.opacity = showYellow ? '1' : '0.5';
      redButton.style.opacity = showRed ? '1' : '0.5';
      cyanButton.style.opacity = showCyan ? '1' : '0.5';
      green2Button.style.opacity = showGreen2 ? '1' : '0.5';
      orangeButton.style.opacity = showOrange ? '1' : '0.5';
      
      // 更新暂停按钮状态
      if (isPaused) {
        pauseButton.textContent = '继续';
        pauseButton.style.background = '#4ecdc4';
        pauseButton.style.borderColor = '#4ecdc4';
      } else {
        pauseButton.textContent = '暂停';
        pauseButton.style.background = '#ff6b6b';
        pauseButton.style.borderColor = '#ff6b6b';
      }
    }
    
    function updateChart() {
      const legendState = {
        '蓝色柱状图': showBlue,
        '绿色柱状图': showGreen,
        '黄色柱状图': showYellow,
        '红色柱状图': showRed,
        '青色柱状图': showCyan,
        '深绿色柱状图': showGreen2,
        '橙色柱状图': showOrange
      };
      console.log('Updating chart with legend state:', legendState);
      sortByCurrentVisibleData(legendState);
    }
    
    blueButton.addEventListener('click', () => {
      showBlue = !showBlue;
      console.log('Blue button clicked, showBlue:', showBlue);
      updateButtonStates();
      updateChart();
    });
    
    greenButton.addEventListener('click', () => {
      showGreen = !showGreen;
      console.log('Green button clicked, showGreen:', showGreen);
      updateButtonStates();
      updateChart();
    });

    yellowButton.addEventListener('click', () => {
      showYellow = !showYellow;
      console.log('Yellow button clicked, showYellow:', showYellow);
      updateButtonStates();
      updateChart();
    });

    redButton.addEventListener('click', () => {
      showRed = !showRed;
      console.log('Red button clicked, showRed:', showRed);
      updateButtonStates();
      updateChart();
    });

    cyanButton.addEventListener('click', () => {
      showCyan = !showCyan;
      console.log('Cyan button clicked, showCyan:', showCyan);
      updateButtonStates();
      updateChart();
    });

    green2Button.addEventListener('click', () => {
      showGreen2 = !showGreen2;
      console.log('Green2 button clicked, showGreen2:', showGreen2);
      updateButtonStates();
      updateChart();
    });

    orangeButton.addEventListener('click', () => {
      showOrange = !showOrange;
      console.log('Orange button clicked, showOrange:', showOrange);
      updateButtonStates();
      updateChart();
    });
    
    // 暂停/继续按钮事件
    pauseButton.addEventListener('click', () => {
      isPaused = !isPaused;
      
      if (isPaused) {
        // 暂停更新
        stopAutoUpdate();
        console.log('Data updates paused');
      } else {
        // 继续更新
        startAutoUpdate();
        console.log('Data updates resumed');
      }
      
      updateButtonStates();
    });
    
    buttonContainer.appendChild(blueButton);
    buttonContainer.appendChild(greenButton);
    buttonContainer.appendChild(yellowButton);
    buttonContainer.appendChild(redButton);
    buttonContainer.appendChild(cyanButton);
    buttonContainer.appendChild(green2Button);
    buttonContainer.appendChild(orangeButton);
    buttonContainer.appendChild(pauseButton); // 添加暂停按钮
    container.appendChild(buttonContainer);
    
    // 初始化按钮状态
    updateButtonStates();
  }
  
  // 创建控制按钮
  createControlButtons();

  // Return control API
  return {
    chart: myChart,
    updateDataValues,
    renderSeries,
    updateOnce,
    startAutoUpdate,
    stopAutoUpdate,
    sortByTotalValue,
    sortByCurrentVisibleData,
    setShowGreenBars: (next) => {
      // 现在通过图例控制，这个方法保留用于兼容性
      console.log('setShowGreenBars called with:', next);
    },
    setUpdateInterval: (ms) => {
      if (typeof ms !== 'number' || ms <= 0) return;
      updateIntervalMs = Math.max(100, ms);
      if (intervalId != null) {
        stopAutoUpdate();
        startAutoUpdate();
      }
    },
    getConfig: () => ({ ...config }),
         getData: () => ({ data: [...originalData] }),
         destroy: () => {
       stopAutoUpdate();
       clearTimeout(resizeTimeout);
       window.removeEventListener('resize', handleResize);
       // 清理控制按钮
       const buttonContainer = document.querySelector('.chart-controls');
       if (buttonContainer) {
         buttonContainer.remove();
       }
       myChart.dispose();
     },
    getPauseState: () => isPaused,
    setPauseState: (state) => {
      isPaused = state;
      if (state) {
        stopAutoUpdate();
        console.log('Data updates paused');
      } else {
        startAutoUpdate();
        console.log('Data updates resumed');
      }
    },
    // 手动更新函数，用于测试
    manualUpdate: () => {
      console.log('Manual update triggered');
      updateOnce();
    },
    // 获取当前显示状态
    getVisibilityState: () => ({
      showBlue,
      showGreen,
      showYellow,
      showRed,
      showCyan,
      showGreen2,
      showOrange,
      isPaused
    })
  };
}

// Auto-initialize with default container for current page usage
const barRaceInstance = createBarRaceChart('container', {
  showGreenBars: true,
  updateIntervalMs: 1000,  // 减少更新间隔到1秒，让数据更新更频繁
  dataCount: 35,           // 增加到35个柱状图
  maxValue: 200,
  animationDuration: 1500,  // 减少动画时间到1.5秒
  barColors: ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452'] // 7种颜色
});

// Expose to global for debugging/control if needed
window.barRaceInstance = barRaceInstance;




